package spring.cloud.tasks.executor.listener.task_execute;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.executor.listener.ListenerHolder;
import spring.cloud.tasks.executor.listener.config.ConfigurationNode;
import spring.cloud.tasks.executor.node.TaskNodePaths;
import spring.cloud.tasks.executor.task.TaskExecutor;

/**
 * 作业控制监听管理器.
 */
@Slf4j
@Setter
@Getter
public class TaskExecuteListenerHolder extends ListenerHolder {

    public boolean isShutdown = false;

    public TaskExecuteListenerHolder(final TaskExecutor taskExecutor) {
        super(taskExecutor);
    }

    @Override
    public void start() {
        nodeCacheOrTreeCacheManager.addTreeCacheListener(TaskNodePaths.getTaskNodePath(taskId, String.format(ExecutorNode.EXECUTOR_RUN_ONE_TIME, executorId)), 0, new TriggerTaskRunAtOnceListener(this));
        nodeCacheOrTreeCacheManager.addTreeCacheListener(TaskNodePaths.getTaskNodePath(taskId, String.format(ExecutorNode.EXECUTOR_STOP_ONE_TIME, executorId)), 0, new TriggerTaskStopAtOnceListener(this));
        nodeCacheOrTreeCacheManager.addTreeCacheListener(TaskNodePaths.getTaskNodePath(taskId, ConfigurationNode.TO_DELETE), 0, new DeleteTaskListener(this));
    }

    @Override
    public void stop() {
        super.stop();
        isShutdown = true;
        nodeCacheOrTreeCacheManager.closeTreeCache(TaskNodePaths.getTaskNodePath(taskId, String.format(ExecutorNode.EXECUTOR_RUN_ONE_TIME, executorId)), 0);
        nodeCacheOrTreeCacheManager.closeTreeCache(TaskNodePaths.getTaskNodePath(taskId, String.format(ExecutorNode.EXECUTOR_STOP_ONE_TIME, executorId)), 0);
        nodeCacheOrTreeCacheManager.closeTreeCache(TaskNodePaths.getTaskNodePath(taskId, ConfigurationNode.TO_DELETE), 0);
    }

}
